//
//  QADetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/10.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "CommonQAModel.h"

#import "QADetailListCell.h"
#import "CommonEvaluateBottomView.h"

#import "QADetailSectionHeaderView.h"
#import "QADetailFoldFooterView.h"

#import "QADetailHeaderView.h"
#import "ReportReasonViewController.h"

#import "QADetailViewController.h"

@interface QADetailViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) QADetailHeaderView *headerView;

@property (nonatomic, strong) CommonEvaluateBottomView *bottomView;

@property (nonatomic, assign) BOOL isFold;

@property (nonatomic, strong) CommonQAModel *model;


@property (nonatomic, strong) CommonAnswerModel *aimModel;



@end

@implementation QADetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_QADetail];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)initView {

    self.isFold = YES;
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(Bottom_SafeHeight + 60);
    }];
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.bottomView.mas_top);
    }];
    
    [self.tableview reloadData];


    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitleColor:UIColorHex(0x666666) forState:UIControlStateNormal];

    [rightBtn setImage:[UIImage imageNamed:@"more_icon"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    rightBtn.frame = CGRectMake(0,0,40,30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItems =@[rightItem];
    
    [self initViewAction];
}

- (void)moreAction {
    
    WEAKSELF
     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
     UIAlertAction *liveAction = [UIAlertAction actionWithTitle:@"举报"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction *action) {

         ReportReasonViewController *vc = [[ReportReasonViewController alloc] init];
         vc.baseId = self.model.mqId;
         vc.level = @"1";
         vc.type = BAReportType_qa;
         [weakSelf.navigationController pushViewController:vc animated:YES];
         
     }];
     
     UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消"
                                            style:UIAlertActionStyleCancel
                                          handler:^(UIAlertAction *action) {

     }];
     
     [alertController addAction:liveAction];
     [alertController addAction:cancleAction];
     [alertController setModalPresentationStyle:UIModalPresentationPopover];
     [self presentViewController:alertController animated:YES completion:nil];
}

- (void)initViewAction {

    WEAKSELF
    self.bottomView.CommonEvaluateBottomViewBlock = ^(CommunityActionType type) {
        [weakSelf share];
    };
}

#pragma mark Share
- (void)share {
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?mqId=%@&replyUserId=%@&myCode=%@",BA_GlobalH5_Domain,@"/answerDetailShare",self.mqId,[TTUserModel sharedObject].userId,[TTUserModel sharedObject].myCode];
    model.title = self.model.title;
    model.content = self.model.content;
    model.image = [UIImage imageNamed:@"ba_logo"];
    [[TT_ShareManager share] callShareViewWithModel:model];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    //判断后将tag变回原来的样子
    self.bottomView.contentTF.placeholder = @"说说您的见解...";
    self.bottomView.contentTF.tag = DetailreplyType_post;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    switch (textField.tag) {
        case DetailreplyType_post:{
            [self request_postEvaWithType:DetailreplyType_post];
        } break;
        default:
            break;
    }
    
    //判断后将tag变回原来的样子
    self.bottomView.contentTF.placeholder = @"说说您的见解...";
    self.bottomView.contentTF.tag = DetailreplyType_post;

    return YES;
}
    
#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat naviH = 100;

//    导航栏设置
    if (scrollView.contentOffset.y > naviH) {

        self.title = self.model.title;
    } else {
        self.title = @"";
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case QADetailSectionType_highQuality:{
            
            if (self.isFold) {
                if (self.model.goodAnswerList.count >2) {
                    return 2;
                } else {
                    return self.model.goodAnswerList.count;
                }
            } else {
                return self.model.goodAnswerList.count;
            }
        } break;
        case ServiceCatNaviType_marvellous:{

            return self.model.ordinaryAnswerList.count;

        } break;
        default:
            break;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    switch (section) {
        case QADetailSectionType_highQuality:{
            
            if (self.model.goodAnswerList.count >0) {
                return 50;
            } else {
                return CGFLOAT_MIN;
            }
            
        } break;
        case ServiceCatNaviType_marvellous:{

            if (self.model.ordinaryAnswerList.count >0) {
                return 50;
            } else {
                return CGFLOAT_MIN;
            }
            
        } break;
        default:{
            return CGFLOAT_MIN;
        }; break;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case QADetailSectionType_highQuality:{
            return [QADetailListCell calculateHeightWithModel:self.model.goodAnswerList[indexPath.row]];
        } break;
        case ServiceCatNaviType_marvellous:{
            return [QADetailListCell calculateHeightWithModel:self.model.ordinaryAnswerList[indexPath.row]];
        } break;
        default:{
            return CGFLOAT_MIN;
        } break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    switch (section) {
        case QADetailSectionType_highQuality:{
            
            if (self.model.goodAnswerList.count >2) {
                return 40;
            } else {
                return CGFLOAT_MIN;
            }
        } break;
        case ServiceCatNaviType_marvellous:{
            return CGFLOAT_MIN;
        } break;
        default:
            break;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    QADetailSectionHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"QADetailSectionHeaderView" owner:nil options:nil].firstObject;
    
    switch (section) {
        case QADetailSectionType_highQuality:{
            sectionHeader.sectionTitleLab.text =[NSString stringWithFormat:@"优质回答(%lu)",(unsigned long)self.model.goodAnswerList.count];
        } break;
        case ServiceCatNaviType_marvellous:{
            sectionHeader.sectionTitleLab.text =[NSString stringWithFormat:@"精彩回答(%lu)",(unsigned long)self.model.ordinaryAnswerList.count];
        } break;
        default:
            break;
    }
    
    return sectionHeader;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    WEAKSELF
    switch (section) {
        case QADetailSectionType_highQuality:{
            
            QADetailFoldFooterView *sectionFooter = [[NSBundle mainBundle] loadNibNamed:@"QADetailFoldFooterView" owner:nil options:nil].firstObject;

            if (self.isFold) {
                sectionFooter.mainTitleLab.text = @"展开";
                [sectionFooter.iconImg setImage:[UIImage imageNamed:@"down_blue"]];
            } else {
                sectionFooter.mainTitleLab.text = @"收起";
                [sectionFooter.iconImg setImage:[UIImage imageNamed:@"up_blue"]];
            }
            
            [sectionFooter addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
               
                weakSelf.isFold = !weakSelf.isFold;
                [weakSelf.tableview reloadData];

            }];
            
            return sectionFooter;
            
        } break;
        case ServiceCatNaviType_marvellous:{

        } break;
        default:
            break;
    }
    return [UIView new];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    switch (indexPath.section) {
        case QADetailSectionType_highQuality:{

            QADetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QADetailListCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            CommonAnswerModel *model = self.model.goodAnswerList[indexPath.row];
            [cell fillWithModel:model Type:QADetailSectionType_highQuality];
            
            cell.QADetailListCellBlock = ^{
                weakSelf.aimModel = model;
                [weakSelf request_postThumbWithType:DetailreplyType_user isZan:model.isZan];
            };
            return cell;
            
        } break;
        case ServiceCatNaviType_marvellous:{

            QADetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QADetailListCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            
            CommonAnswerModel *model = self.model.ordinaryAnswerList[indexPath.row];
            [cell fillWithModel:model Type:ServiceCatNaviType_marvellous];

            cell.QADetailListCellBlock = ^{
                weakSelf.aimModel = model;
                [weakSelf request_postThumbWithType:DetailreplyType_user isZan:model.isZan];
            };
            
            return cell;
        } break;
        default:
            break;
    }
    
    QADetailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QADetailListCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;

}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"QADetailListCell" bundle:nil] forCellReuseIdentifier:@"QADetailListCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_QADetail];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_more];
        }];
    }
    return _tableview;
}
    
- (QADetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[NSBundle mainBundle] loadNibNamed:@"QADetailHeaderView" owner:nil options:nil].firstObject;
    }
    return _headerView;
}

- (CommonEvaluateBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"CommonEvaluateBottomView"owner:nil options:nil].firstObject;
        _bottomView.contentTF.delegate = self;
        _bottomView.evaBtnWidth.constant = CGFLOAT_MIN;
        _bottomView.thumbBtnWidth.constant = CGFLOAT_MIN;
    }
    return _bottomView;
}

//

- (void)request_QADetail {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:self.mqId forKey:@"mqId"];
    [dic setValue:@"" forKey:@"title"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_QADetail];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    weakSelf.model = [CommonQAModel modelWithDictionary:resultDic];
                    
                    NSArray *goodAnswerList = [resultDic valueForKey:@"goodAnswerList"];
                    NSDictionary *ordinaryAnswerList = [resultDic valueForKey:@"ordinaryAnswerList"];
                    
                    if ([goodAnswerList isKindOfClass:[NSArray class]]) {
                        weakSelf.model.goodAnswerList = @[].mutableCopy;
                        for (NSDictionary *goodDic in goodAnswerList) {
                            CommonAnswerModel *goodModel = [CommonAnswerModel modelWithDictionary:goodDic];
                            [weakSelf.model.goodAnswerList addObject:goodModel];
                        }
                    }
                    
                    weakSelf.model.ordinaryAnswerList = @[].mutableCopy;
                    if ([ordinaryAnswerList isKindOfClass:[NSDictionary class]]) {
                        NSArray *list = [ordinaryAnswerList valueForKey:@"list"];
                        
                        if ([list isKindOfClass:[NSArray class]]) {
                            for (NSDictionary *ordinaryDic in list) {
                                CommonAnswerModel *ordinaryModel = [CommonAnswerModel modelWithDictionary:ordinaryDic];
                                [weakSelf.model.ordinaryAnswerList addObject:ordinaryModel];
                            }
                        }
                    }
                    
                    [weakSelf.headerView fillWithModel:weakSelf.model];
                    
                    weakSelf.headerView.frame = CGRectMake(0, 0, TTScreenWidth, [QADetailHeaderView calculateHeightWithModel:weakSelf.model]);
                    weakSelf.tableview.tableHeaderView = weakSelf.headerView;
                    weakSelf.headerView.autoresizingMask = UIViewAutoresizingNone;
                    [weakSelf.tableview reloadData];
                }
            } else {
                
                [TT_Alert alert:[data valueForKey:@"message"] doneAction:^{
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
    }];
}

- (void)request_more {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    [t setValue:self.mqId forKey:@"mqId"];
    [t setValue:@"2" forKey:@"isOptimization"];
    [t setValue:@"2" forKey:@"isSelected"];

    [t setValue:@"2" forKey:@"isDel"];

    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_QAMoreAnswer];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                                        
                    if (weakSelf.pageNum == 1) {
                        weakSelf.model.ordinaryAnswerList = @[].mutableCopy;
                    }
                    
                        NSArray *list = [resultDic valueForKey:@"list"];
                        
                        if ([list isKindOfClass:[NSArray class]]) {
                            for (NSDictionary *ordinaryDic in list) {
                                CommonAnswerModel *ordinaryModel = [CommonAnswerModel modelWithDictionary:ordinaryDic];
                                [weakSelf.model.ordinaryAnswerList addObject:ordinaryModel];
                            }
                        }
                                        
                    [weakSelf.tableview reloadData];
                }
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
    }];
}

- (void)request_postEvaWithType:(DetailreplyType)type {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.bottomView.contentTF.text forKey:@"content"];
    
    switch (type) {
        case DetailreplyType_post:{
            
            [dic setValue:self.mqId forKey:@"baseId"];
            [dic setValue:@"2" forKey:@"level"];
            [dic setValue:@"2" forKey:@"source"];//问答只能用户提问  所以source肯定是2
            [dic setValue:self.model.userId forKey:@"userId"];
        } break;
        case DetailreplyType_user:{
        } break;
        case DetailreplyType_replayUser:{
        } break;
        default:
            break;
    }
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [dic setValue:@"1" forKey:@"mold"];
    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"3" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在发布评论"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.bottomView.contentTF.text = @"";
                [weakSelf.view endEditing:YES];
                
                [weakSelf request_QADetail];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}


- (void)request_postThumbWithType:(DetailreplyType)type isZan:(NSString *)isZan {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
        
    //点赞评论          cpId
    [dic setValue:self.aimModel.uaId forKey:@"baseId"];
    [dic setValue:@"2" forKey:@"level"];

    [dic setValue:self.aimModel.source forKey:@"source"];
    [dic setValue:self.aimModel.baseId forKey:@"userId"];
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    if (isZan.length > 0) {
        [dic setValue:@"5" forKey:@"mold"];
        [dic setValue:isZan forKey:@"otherId"];
    } else {
        [dic setValue:@"2" forKey:@"mold"];
    }

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"3" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSString *isZan = [data valueForKey:@"data"];
                if ([isZan isKindOfClass:[NSString class]]) {
                    weakSelf.aimModel.isZan = isZan;
                    if (isZan.length > 0) {
                        weakSelf.aimModel.laudNumber++;
                    } else {
                        weakSelf.aimModel.laudNumber--;
                    }
                }
                
//                    weakSelf.dataArray[index].isZan = isZan;
//                    if (isZan.length > 0) {
//                        weakSelf.dataArray[index].likes++;
//                    } else {
//                        weakSelf.dataArray[index].likes--;
//                    }
                [weakSelf.tableview reloadData];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

@end
